import { 
  createWeChatLoginSession, 
  checkWeChatLoginStatus, 
  handleWeChatCallback,
  getWeChatUserByState,
  clearWeChatSession,
  type WeChatLoginRequest,
  type WeChatUserInfo
} from '../services/wechat-auth';
import { generateToken, type JWTPayload } from '../services/auth';

// 创建微信扫码登录会话
export async function handleWeChatLogin(req: Request): Promise<Response> {
  try {
    const body = await req.json() as WeChatLoginRequest;
    const result = await createWeChatLoginSession(body.state);
    
    return Response.json(result);
  } catch (error) {
    console.error('创建微信登录会话失败:', error);
    return Response.json({
      success: false,
      message: '创建登录会话失败'
    }, { status: 500 });
  }
}

// 检查微信扫码登录状态
export function handleWeChatStatus(req: Request): Response {
  try {
    const url = new URL(req.url);
    const state = url.searchParams.get('state');
    
    if (!state) {
      return Response.json({
        success: false,
        message: '缺少 state 参数'
      }, { status: 400 });
    }
    
    const result = checkWeChatLoginStatus(state);
    return Response.json(result);
  } catch (error) {
    console.error('检查微信登录状态失败:', error);
    return Response.json({
      success: false,
      message: '检查登录状态失败'
    }, { status: 500 });
  }
}

// 处理微信授权回调
export async function handleWeChatCallbackRoute(req: Request): Promise<Response> {
  try {
    const url = new URL(req.url);
    const code = url.searchParams.get('code');
    const state = url.searchParams.get('state');
    
    if (!code || !state) {
      return Response.json({
        success: false,
        message: '缺少必要参数'
      }, { status: 400 });
    }
    
    const result = await handleWeChatCallback(code, state);
    
    if (result.success && result.data?.status === 'confirmed') {
      // 生成 JWT token
      const userInfo = result.data.userInfo!;
      const payload: JWTPayload = {
        userId: userInfo.openid,
        username: userInfo.nickname,
        email: userInfo.openid + '@wechat.local'
      };
      
      const token = generateToken(payload);
      
      return Response.json({
        success: true,
        message: '微信登录成功',
        data: {
          token,
          user: {
            id: userInfo.openid,
            username: userInfo.nickname,
            avatar: userInfo.headimgurl,
            source: 'wechat'
          }
        }
      });
    }
    
    return Response.json(result);
  } catch (error) {
    console.error('处理微信回调失败:', error);
    return Response.json({
      success: false,
      message: '处理回调失败'
    }, { status: 500 });
  }
}

// 获取微信用户信息
export function handleWeChatUserInfo(req: Request): Response {
  try {
    const url = new URL(req.url);
    const state = url.searchParams.get('state');
    
    if (!state) {
      return Response.json({
        success: false,
        message: '缺少 state 参数'
      }, { status: 400 });
    }
    
    const userInfo = getWeChatUserByState(state);
    
    if (!userInfo) {
      return Response.json({
        success: false,
        message: '用户信息不存在或已过期'
      }, { status: 404 });
    }
    
    return Response.json({
      success: true,
      message: '获取用户信息成功',
      data: {
        user: userInfo
      }
    });
  } catch (error) {
    console.error('获取微信用户信息失败:', error);
    return Response.json({
      success: false,
      message: '获取用户信息失败'
    }, { status: 500 });
  }
}

// 清理微信登录会话
export function handleWeChatLogout(req: Request): Response {
  try {
    const url = new URL(req.url);
    const state = url.searchParams.get('state');
    
    if (!state) {
      return Response.json({
        success: false,
        message: '缺少 state 参数'
      }, { status: 400 });
    }
    
    clearWeChatSession(state);
    
    return Response.json({
      success: true,
      message: '清理会话成功'
    });
  } catch (error) {
    console.error('清理微信会话失败:', error);
    return Response.json({
      success: false,
      message: '清理会话失败'
    }, { status: 500 });
  }
}
